package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author 郝文雪
 * @date 2022/8/3 22:27
 * @Description 统一异常处理类
 */
//对控制器进行增强（当前类为统一异常封装类）
@ControllerAdvice
@ResponseBody
public class MyException {

    /**
     * 算术异常
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public HashMap<String,Object> myArithmeticException(ArithmeticException e){
        HashMap<String,Object> result=new HashMap<String,Object>();
        result.put("state",-1);
        result.put("msg","算术异常："+e.getMessage());
        result.put("data",null);
        return result;
    }

    @ExceptionHandler(Exception.class)
    public HashMap<String,Object> myException(Exception e){
        HashMap<String,Object> result=new HashMap<String,Object>();
        result.put("state",-1);
        result.put("msg","默认异常："+e.getMessage());
        result.put("data",null);
        return result;
    }
}
